<!-- backend/templates/forecast_generate.html -->
{% extends "base.html" %}

{% block content %}
    <h2 class="mb-4">需求预测生成</h2>
    <div class="row justify-content-center">
        <div class="col-md-6">
            <form id="forecastForm" class="mb-3">
                <div class="mb-3">
                    <label for="fileSelect" class="form-label">选择上传文件</label>
                    <select class="form-select" id="fileSelect" required>
                        <option value="">选择上传文件</option>
                        <!-- 上传文件列表将被填充在这里 -->
                    </select>
                </div>
                <div class="mb-3">
                    <label for="modelType" class="form-label">模型类型</label>
                    <select class="form-select" id="modelType" required>
                        <option value="">选择模型类型</option>
                        <option value="RandomForest">随机森林</option>
                        <option value="LinearRegression">线性回归</option>
                        <!-- 添加其他模型选项 -->
                    </select>
                </div>
                <button type="submit" class="btn btn-primary w-100">生成预测</button>
            </form>
            <div id="message"></div> <!-- 消息显示区域 -->
            <div id="loading" class="text-center" style="display: none;">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 预测结果显示区域 -->
    <div class="row justify-content-center mt-5">
        <div class="col-md-10">
            <h3>预测结果</h3>
            <div id="forecastResults" class="mb-4" style="display: none;">
                <!-- 动态生成的预测结果 -->
                <!-- 包含品类名称 -->
                <div id="forecastResultCards" class="row">
                    <!-- 预测结果卡片将被添加到这里 -->
                </div>
            </div>

            <!-- 预测结果列表 -->
            <h3 class="mt-5">历史预测结果</h3>
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>预测 ID</th>
                        <th>文件名</th> <!-- 新增文件名列 -->
                        <th>生成时间</th>
                        <th>品类</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="forecastTableBody">
                    <!-- 预测结果将被列在此处 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 模态框用于显示详细信息 -->
    <div id="forecastModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span> <!-- 关闭模态框的按钮 -->
            <h2>预测详情</h2>
            <div id="forecastDetails">
                <!-- 详细信息将通过JavaScript填充 -->
            </div>
        </div>
    </div>

    <script>
        // DOM内容加载完成后的事件处理
        document.addEventListener('DOMContentLoaded', () => {
            const forecastForm = document.getElementById('forecastForm'); // 预测生成表单
            const messageDiv = document.getElementById('message'); // 消息显示区域
            const loadingDiv = document.getElementById('loading'); // 加载状态区域
            const forecastTableBody = document.getElementById('forecastTableBody'); // 预测结果表体
            const fileSelect = document.getElementById('fileSelect'); // 上传文件选择框
            const forecastResults = document.getElementById('forecastResults'); // 预测结果显示区域
            const forecastResultCards = document.getElementById('forecastResultCards'); // 预测结果卡片区域

            // 加载上传文件列表到选择框
            const loadUploadedFiles = async () => {
                try {
                    const response = await fetch('/api/data/uploaded_files', {
                        method: 'GET',
                        credentials: 'include' // 包含Cookies
                    });
                    const data = await response.json();
                    if (response.ok) {
                        // 清空选择框并添加上传文件选项
                        fileSelect.innerHTML = `<option value="">选择上传文件</option>`;
                        data.uploaded_files.forEach(file => {
                            const option = document.createElement('option'); // 创建下拉选项
                            option.value = file.id; // 文件ID
                            option.textContent = file.file_name; // 显示文件名
                            fileSelect.appendChild(option); // 将选项添加到选择框
                        });
                    } else {
                        fileSelect.innerHTML = `<option value="">无法加载上传文件</option>`;
                    }
                } catch (error) {
                    console.error('加载上传文件列表失败:', error);
                    fileSelect.innerHTML = `<option value="">加载上传文件时发生错误</option>`;
                }
            };

            // 生成预测的事件处理
            forecastForm.addEventListener('submit', async (e) => {
                e.preventDefault(); // 阻止表单默认提交
                const fileId = document.getElementById('fileSelect').value; // 获取选择的文件ID
                const modelType = document.getElementById('modelType').value; // 获取选择的模型类型

                // 检查必填字段是否填写完整
                if (!fileId || !modelType) {
                    messageDiv.innerHTML = `<div class="alert alert-warning">请填写所有必填字段。</div>`;
                    return;
                }

                // 构建 JSON 数据
                const params = {
                    model_type: modelType, // 模型类型
                    file_id: parseInt(fileId) // 文件ID
                };

                try {
                    loadingDiv.style.display = 'block'; // 显示加载状态
                    messageDiv.innerHTML = ''; // 清空消息区域
                    forecastResults.style.display = 'none'; // 隐藏预测结果区域
                    forecastResultCards.innerHTML = ''; // 清空预测结果卡片

                    const response = await fetch('/api/forecast/generate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json' // 设置内容类型为JSON
                        },
                        credentials: 'include', // 包含Cookies
                        body: JSON.stringify(params) // 将参数转换为JSON字符串
                    });

                    let data; // 用于存放响应数据
                    try {
                        data = await response.json(); // 尝试解析响应为JSON
                    } catch (e) {
                        console.error('解析响应为 JSON 失败:', e);
                        data = null; // 解析失败时置为空
                    }

                    loadingDiv.style.display = 'none'; // 隐藏加载状态

                    if (response.ok) {
                        if (data && data.message) {
                            messageDiv.innerHTML = `<div class="alert alert-success">${data.message}</div>`;
                        } else {
                            messageDiv.innerHTML = `<div class="alert alert-success">预测生成成功。</div>`;
                        }
                        forecastForm.reset(); // 重置表单
                        loadUploadedFiles(); // 重新加载上传文件列表
                        loadForecasts(); // 重新加载预测列表

                        // 显示预测结果
                        if (data.forecast_ids && data.forecast_ids.length > 0) {
                            // 为每个 forecast_id 获取详细信息
                            for (const forecast_id of data.forecast_ids) {
                                const forecastDetails = await fetch(`/api/forecast/details/${forecast_id}`, {
                                    method: 'GET',
                                    credentials: 'include' // 包含Cookies
                                });
                                const forecastData = await forecastDetails.json();
                                if (forecastDetails.ok) {
                                    // 创建预测结果卡片
                                    const card = document.createElement('div');
                                    card.className = 'col-md-6 mb-4'; // 设置卡片样式
                                    card.innerHTML = `
                                        <div class="card">
                                            <div class="card-header">
                                                预测 ID: ${forecastData.id} | 品类: ${forecastData.category}
                                            </div>
                                            <div class="card-body">
                                                <h5 class="card-title">未来一年的需求量预测</h5>
                                                <table class="table table-bordered">
                                                    <thead>
                                                        <tr>
                                                            <th>日期</th>
                                                            <th>预测需求量</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        ${forecastData.demand_forecasts.map(df => `
                                                            <tr>
                                                                <td>${df.forecast_date}</td>
                                                                <td>${df.forecast_quantity}</td>
                                                            </tr>
                                                        `).join('')}
                                                    </tbody>
                                                </table>

                                                <h5 class="card-title">库存补货建议</h5>
                                                <table class="table table-bordered">
                                                    <thead>
                                                        <tr>
                                                            <th>日期</th>
                                                            <th>预测需求量</th>
                                                            <th>当前库存量</th>
                                                            <th>建议补货量</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        ${forecastData.inventory_suggestions.map(sg => `
                                                            <tr>
                                                                <td>${sg.date}</td>
                                                                <td>${sg.forecast_demand}</td>
                                                                <td>${sg.current_inventory}</td>
                                                                <td>${parseInt(sg.reorder_quantity, 10)}</td> <!-- 确保为整数 -->
                                                            </tr>
                                                        `).join('')}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    `;
                                    forecastResultCards.appendChild(card); // 将卡片添加到结果区域
                                }
                            }
                            forecastResults.style.display = 'block'; // 显示预测结果区域
                        }
                    } else {
                        if (data && data.message) {
                            messageDiv.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                        } else {
                            messageDiv.innerHTML = `<div class="alert alert-danger">预测生成失败，请重试。</div>`;
                        }
                    }
                } catch (error) {
                    loadingDiv.style.display = 'none'; // 隐藏加载状态
                    console.error('预测生成失败:', error);
                    messageDiv.innerHTML = `<div class="alert alert-danger">预测生成失败，请重试。</div>`;
                }
            });

            // 加载预测列表
            const loadForecasts = async () => {
                try {
                    const response = await fetch('/api/forecast/list', {
                        method: 'GET',
                        credentials: 'include' // 包含Cookies
                    });
                    const data = await response.json();
                    if (response.ok) {
                        forecastTableBody.innerHTML = ''; // 清空预测表体
                        data.forecasts.forEach(forecast => {
                            const row = document.createElement('tr'); // 创建新行
                            row.innerHTML = `
                                <td>${forecast.id}</td>
                                <td>${forecast.file_name}</td> <!-- 显示存储的文件名，包含原始名称 -->
                                <td>${forecast.timestamp}</td>
                                <td>${forecast.category}</td>
                                <td>
                                    <button class="btn btn-sm btn-primary me-2" onclick="viewForecast(${forecast.id})">查看</button>
                                    <button class="btn btn-sm btn-danger" onclick="deleteForecast(${forecast.id})">删除</button>
                                </td>
                            `;
                            forecastTableBody.appendChild(row); // 将行添加到表体
                        });
                    } else {
                        forecastTableBody.innerHTML = `<tr><td colspan="5" class="text-danger">无法加载预测列表。</td></tr>`;
                    }
                } catch (error) {
                    console.error('加载预测列表失败:', error);
                    forecastTableBody.innerHTML = `<tr><td colspan="5" class="text-danger">加载预测列表时发生错误。</td></tr>`;
                }
            };

            // 查看预测记录
            window.viewForecast = async (forecastId) => {
                try {
                    const response = await fetch(`/api/forecast/details/${forecastId}`, {
                        method: 'GET',
                        credentials: 'include' // 包含Cookies
                    });
                    const data = await response.json();
                    if (response.ok) {
                        // 清空之前的预测结果
                        forecastResultCards.innerHTML = '';

                        // 创建预测结果卡片
                        const card = document.createElement('div');
                        card.className = 'col-md-12 mb-4';
                        card.innerHTML = `
                            <div class="card">
                                <div class="card-header">
                                    预测 ID: ${data.id} | 品类: ${data.category}
                                </div>
                                <div class="card-body">
                                    <h5 class="card-title">未来一年的需求量预测</h5>
                                    <table class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <th>日期</th>
                                                <th>预测需求量</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            ${data.demand_forecasts.map(df => `
                                                <tr>
                                                    <td>${df.forecast_date}</td>
                                                    <td>${df.forecast_quantity}</td>
                                                </tr>
                                            `).join('')}
                                        </tbody>
                                    </table>

                                    <h5 class="card-title">库存补货建议</h5>
                                    <table class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <th>日期</th>
                                                <th>预测需求量</th>
                                                <th>当前库存量</th>
                                                <th>建议补货量</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            ${data.inventory_suggestions.map(sg => `
                                                <tr>
                                                    <td>${sg.date}</td>
                                                    <td>${sg.forecast_demand}</td>
                                                    <td>${sg.current_inventory}</td>
                                                    <td>${parseInt(sg.reorder_quantity, 10)}</td> <!-- 确保为整数 -->
                                                </tr>
                                            `).join('')}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        `;
                        forecastResultCards.appendChild(card); // 添加预测结果卡片
                        forecastResults.style.display = 'block'; // 显示预测结果区域
                        // 滚动到预测结果区域
                        forecastResults.scrollIntoView({ behavior: 'smooth' });
                    } else {
                        alert(`无法获取预测详细信息: ${data.message}`);
                    }
                } catch (error) {
                    console.error('查看预测失败:', error);
                    alert('查看预测失败，请重试。');
                }
            };

            // 删除预测记录
            window.deleteForecast = async (forecastId) => {
                if (!confirm(`确定要删除预测 ID ${forecastId} 吗？`)) return; // 确认删除操作

                try {
                    const response = await fetch(`/api/forecast/delete/${forecastId}`, {
                        method: 'DELETE',
                        credentials: 'include' // 包含Cookies
                    });
                    const data = await response.json();
                    if (response.ok) {
                        messageDiv.innerHTML = `<div class="alert alert-success">${data.message}</div>`; // 显示成功消息
                        loadForecasts(); // 重新加载预测列表
                        // 如果删除的预测正在显示，隐藏预测结果
                        forecastResults.style.display = 'none'; // 隐藏结果区域
                        forecastResultCards.innerHTML = ''; // 清空预测卡片区域
                    } else {
                        messageDiv.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                    }
                } catch (error) {
                    console.error('删除预测失败:', error);
                    messageDiv.innerHTML = `<div class="alert alert-danger">删除预测失败，请重试。</div>`;
                }
            };

            // 关闭模态框的函数
            function closeModal() {
                const modal = document.getElementById("forecastModal"); // 获取模态框
                modal.style.display = "none"; // 隐藏模态框
                const forecastDetailsDiv = document.getElementById("forecastDetails"); // 获取预测详情区域
                forecastDetailsDiv.innerHTML = ""; // 清空预测详情
            }

            // 点击模态框外部关闭模态框
            window.onclick = function(event) {
                const modal = document.getElementById("forecastModal"); // 获取模态框
                if (event.target == modal) {
                    modal.style.display = "none"; // 隐藏模态框
                    const forecastDetailsDiv = document.getElementById("forecastDetails"); // 获取预测详情区域
                    forecastDetailsDiv.innerHTML = ""; // 清空预测详情
                }
            }

            // 初始加载上传文件列表和预测列表
            loadUploadedFiles(); // 加载上传文件列表
            loadForecasts(); // 加载预测列表
        });
    </script>
{% endblock %}
